home *** CD-ROM | disk | FTP | other *** search
/ IRIX Base Documentation 2002 November / SGI IRIX Base Documentation 2002 November.iso / usr / share / catman / u_man / cat1 / perlcall.z / perlcall
Encoding:
Text File  |  2002-10-03  |  78.7 KB  |  2,377 lines

  1.  
  2.  
  3.  
  4. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  5.  
  6.  
  7.  
  8. NNNNAAAAMMMMEEEE
  9.      perlcall - Perl calling conventions from C
  10.  
  11. DDDDEEEESSSSCCCCRRRRIIIIPPPPTTTTIIIIOOOONNNN
  12.      The purpose of this document is to show you how to call Perl subroutines
  13.      directly from C, i.e., how to write _c_a_l_l_b_a_c_k_s.
  14.  
  15.      Apart from discussing the C interface provided by Perl for writing
  16.      callbacks the document uses a series of examples to show how the
  17.      interface actually works in practice.  In addition some techniques for
  18.      coding callbacks are covered.
  19.  
  20.      Examples where callbacks are necessary include
  21.  
  22.      +o An Error Handler
  23.           You have created an XSUB interface to an application's C API.
  24.  
  25.           A fairly common feature in applications is to allow you to define a
  26.           C function that will be called whenever something nasty occurs. What
  27.           we would like is to be able to specify a Perl subroutine that will
  28.           be called instead.
  29.  
  30.      +o An Event Driven Program
  31.           The classic example of where callbacks are used is when writing an
  32.           event driven program like for an X windows application.  In this
  33.           case you register functions to be called whenever specific events
  34.           occur, e.g., a mouse button is pressed, the cursor moves into a
  35.           window or a menu item is selected.
  36.  
  37.      Although the techniques described here are applicable when embedding Perl
  38.      in a C program, this is not the primary goal of this document.  There are
  39.      other details that must be considered and are specific to embedding Perl.
  40.      For details on embedding Perl in C refer to the _p_e_r_l_e_m_b_e_d manpage.
  41.  
  42.      Before you launch yourself head first into the rest of this document, it
  43.      would be a good idea to have read the following two documents - the
  44.      _p_e_r_l_x_s manpage and the _p_e_r_l_g_u_t_s manpage.
  45.  
  46. TTTTHHHHEEEE PPPPEEEERRRRLLLL____CCCCAAAALLLLLLLL FFFFUUUUNNNNCCCCTTTTIIIIOOOONNNNSSSS
  47.      Although this stuff is easier to explain using examples, you first need
  48.      be aware of a few important definitions.
  49.  
  50.      Perl has a number of C functions that allow you to call Perl subroutines.
  51.      They are
  52.  
  53.          I32 perl_call_sv(SV* sv, I32 flags) ;
  54.          I32 perl_call_pv(char *subname, I32 flags) ;
  55.          I32 perl_call_method(char *methname, I32 flags) ;
  56.          I32 perl_call_argv(char *subname, I32 flags, register char **argv) ;
  57.  
  58.      The key function is _p_e_r_l__c_a_l_l__s_v.  All the other functions are fairly
  59.      simple wrappers which make it easier to call Perl subroutines in special
  60.  
  61.  
  62.  
  63.                                                                         PPPPaaaaggggeeee 1111
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  71.  
  72.  
  73.  
  74.      cases. At the end of the day they will all call _p_e_r_l__c_a_l_l__s_v to invoke
  75.      the Perl subroutine.
  76.  
  77.      All the _p_e_r_l__c_a_l_l_* functions have a flags parameter which is used to
  78.      pass a bit mask of options to Perl.  This bit mask operates identically
  79.      for each of the functions.  The settings available in the bit mask are
  80.      discussed in the section on _F_L_A_G _V_A_L_U_E_S.
  81.  
  82.      Each of the functions will now be discussed in turn.
  83.  
  84.      perl_call_sv
  85.           _p_e_r_l__c_a_l_l__s_v takes two parameters, the first, sv, is an SV*.  This
  86.           allows you to specify the Perl subroutine to be called either as a C
  87.           string (which has first been converted to an SV) or a reference to a
  88.           subroutine. The section, _U_s_i_n_g _p_e_r_l__c_a_l_l__s_v, shows how you can make
  89.           use of _p_e_r_l__c_a_l_l__s_v.
  90.  
  91.      perl_call_pv
  92.           The function, _p_e_r_l__c_a_l_l__p_v, is similar to _p_e_r_l__c_a_l_l__s_v except it
  93.           expects its first parameter to be a C char* which identifies the
  94.           Perl subroutine you want to call, e.g., perl_call_pv("fred", 0).  If
  95.           the subroutine you want to call is in another package, just include
  96.           the package name in the string, e.g., "pkg::fred".
  97.  
  98.      perl_call_method
  99.           The function _p_e_r_l__c_a_l_l__m_e_t_h_o_d is used to call a method from a Perl
  100.           class.  The parameter methname corresponds to the name of the method
  101.           to be called.  Note that the class that the method belongs to is
  102.           passed on the Perl stack rather than in the parameter list. This
  103.           class can be either the name of the class (for a static method) or a
  104.           reference to an object (for a virtual method).  See the _p_e_r_l_o_b_j
  105.           manpage for more information on static and virtual methods and the
  106.           section on _U_s_i_n_g _p_e_r_l__c_a_l_l__m_e_t_h_o_d for an example of using
  107.           _p_e_r_l__c_a_l_l__m_e_t_h_o_d.
  108.  
  109.      perl_call_argv
  110.           _p_e_r_l__c_a_l_l__a_r_g_v calls the Perl subroutine specified by the C string
  111.           stored in the subname parameter. It also takes the usual flags
  112.           parameter.  The final parameter, argv, consists of a NULL terminated
  113.           list of C strings to be passed as parameters to the Perl subroutine.
  114.           See _U_s_i_n_g _p_e_r_l__c_a_l_l__a_r_g_v.
  115.  
  116.      All the functions return an integer. This is a count of the number of
  117.      items returned by the Perl subroutine. The actual items returned by the
  118.      subroutine are stored on the Perl stack.
  119.  
  120.      As a general rule you should _a_l_w_a_y_s check the return value from these
  121.      functions.  Even if you are expecting only a particular number of values
  122.      to be returned from the Perl subroutine, there is nothing to stop someone
  123.      from doing something unexpected - don't say you haven't been warned.
  124.  
  125.  
  126.  
  127.  
  128.  
  129.                                                                         PPPPaaaaggggeeee 2222
  130.  
  131.  
  132.  
  133.  
  134.  
  135.  
  136. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  137.  
  138.  
  139.  
  140. FFFFLLLLAAAAGGGG VVVVAAAALLLLUUUUEEEESSSS
  141.      The flags parameter in all the _p_e_r_l__c_a_l_l_* functions is a bit mask which
  142.      can consist of any combination of the symbols defined below, OR'ed
  143.      together.
  144.  
  145.      GGGG____VVVVOOOOIIIIDDDD
  146.  
  147.      Calls the Perl subroutine in a void context.
  148.  
  149.      This flag has 2 effects:
  150.  
  151.      1.   It indicates to the subroutine being called that it is executing in
  152.           a void context (if it executes _w_a_n_t_a_r_r_a_y the result will be the
  153.           undefined value).
  154.  
  155.      2.   It ensures that nothing is actually returned from the subroutine.
  156.  
  157.      The value returned by the _p_e_r_l__c_a_l_l_* function indicates how many items
  158.      have been returned by the Perl subroutine - in this case it will be 0.
  159.  
  160.      GGGG____SSSSCCCCAAAALLLLAAAARRRR
  161.  
  162.      Calls the Perl subroutine in a scalar context.  This is the default
  163.      context flag setting for all the _p_e_r_l__c_a_l_l_* functions.
  164.  
  165.      This flag has 2 effects:
  166.  
  167.      1.   It indicates to the subroutine being called that it is executing in
  168.           a scalar context (if it executes _w_a_n_t_a_r_r_a_y the result will be
  169.           false).
  170.  
  171.      2.   It ensures that only a scalar is actually returned from the
  172.           subroutine.  The subroutine can, of course,  ignore the _w_a_n_t_a_r_r_a_y
  173.           and return a list anyway. If so, then only the last element of the
  174.           list will be returned.
  175.  
  176.      The value returned by the _p_e_r_l__c_a_l_l_* function indicates how many items
  177.      have been returned by the Perl subroutine - in this case it will be
  178.      either 0 or 1.
  179.  
  180.      If 0, then you have specified the G_DISCARD flag.
  181.  
  182.      If 1, then the item actually returned by the Perl subroutine will be
  183.      stored on the Perl stack - the section _R_e_t_u_r_n_i_n_g _a _S_c_a_l_a_r shows how to
  184.      access this value on the stack.  Remember that regardless of how many
  185.      items the Perl subroutine returns, only the last one will be accessible
  186.      from the stack - think of the case where only one value is returned as
  187.      being a list with only one element.  Any other items that were returned
  188.      will not exist by the time control returns from the _p_e_r_l__c_a_l_l_* function.
  189.      The section _R_e_t_u_r_n_i_n_g _a _l_i_s_t _i_n _a _s_c_a_l_a_r _c_o_n_t_e_x_t shows an example of this
  190.      behavior.
  191.  
  192.  
  193.  
  194.  
  195.                                                                         PPPPaaaaggggeeee 3333
  196.  
  197.  
  198.  
  199.  
  200.  
  201.  
  202. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  203.  
  204.  
  205.  
  206.      GGGG____AAAARRRRRRRRAAAAYYYY
  207.  
  208.      Calls the Perl subroutine in a list context.
  209.  
  210.      As with G_SCALAR, this flag has 2 effects:
  211.  
  212.      1.   It indicates to the subroutine being called that it is executing in
  213.           an array context (if it executes _w_a_n_t_a_r_r_a_y the result will be true).
  214.  
  215.      2.   It ensures that all items returned from the subroutine will be
  216.           accessible when control returns from the _p_e_r_l__c_a_l_l_* function.
  217.  
  218.      The value returned by the _p_e_r_l__c_a_l_l_* function indicates how many items
  219.      have been returned by the Perl subroutine.
  220.  
  221.      If 0, then you have specified the G_DISCARD flag.
  222.  
  223.      If not 0, then it will be a count of the number of items returned by the
  224.      subroutine. These items will be stored on the Perl stack.  The section
  225.      _R_e_t_u_r_n_i_n_g _a _l_i_s_t _o_f _v_a_l_u_e_s gives an example of using the G_ARRAY flag and
  226.      the mechanics of accessing the returned items from the Perl stack.
  227.  
  228.      GGGG____DDDDIIIISSSSCCCCAAAARRRRDDDD
  229.  
  230.      By default, the _p_e_r_l__c_a_l_l_* functions place the items returned from by
  231.      the Perl subroutine on the stack.  If you are not interested in these
  232.      items, then setting this flag will make Perl get rid of them
  233.      automatically for you.  Note that it is still possible to indicate a
  234.      context to the Perl subroutine by using either G_SCALAR or G_ARRAY.
  235.  
  236.      If you do not set this flag then it is _v_e_r_y important that you make sure
  237.      that any temporaries (i.e., parameters passed to the Perl subroutine and
  238.      values returned from the subroutine) are disposed of yourself.  The
  239.      section _R_e_t_u_r_n_i_n_g _a _S_c_a_l_a_r gives details of how to dispose of these
  240.      temporaries explicitly and the section _U_s_i_n_g _P_e_r_l _t_o _d_i_s_p_o_s_e _o_f
  241.      _t_e_m_p_o_r_a_r_i_e_s discusses the specific circumstances where you can ignore the
  242.      problem and let Perl deal with it for you.
  243.  
  244.      GGGG____NNNNOOOOAAAARRRRGGGGSSSS
  245.  
  246.      Whenever a Perl subroutine is called using one of the _p_e_r_l__c_a_l_l_*
  247.      functions, it is assumed by default that parameters are to be passed to
  248.      the subroutine.  If you are not passing any parameters to the Perl
  249.      subroutine, you can save a bit of time by setting this flag.  It has the
  250.      effect of not creating the @_ array for the Perl subroutine.
  251.  
  252.      Although the functionality provided by this flag may seem
  253.      straightforward, it should be used only if there is a good reason to do
  254.      so.  The reason for being cautious is that even if you have specified the
  255.      G_NOARGS flag, it is still possible for the Perl subroutine that has been
  256.      called to think that you have passed it parameters.
  257.  
  258.  
  259.  
  260.  
  261.                                                                         PPPPaaaaggggeeee 4444
  262.  
  263.  
  264.  
  265.  
  266.  
  267.  
  268. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  269.  
  270.  
  271.  
  272.      In fact, what can happen is that the Perl subroutine you have called can
  273.      access the @_ array from a previous Perl subroutine.  This will occur
  274.      when the code that is executing the _p_e_r_l__c_a_l_l_* function has itself been
  275.      called from another Perl subroutine. The code below illustrates this
  276.  
  277.          sub fred
  278.            { print "@_\n"  }
  279.  
  280.          sub joe
  281.            { &fred }
  282.  
  283.          &joe(1,2,3) ;
  284.  
  285.      This will print
  286.  
  287.          1 2 3
  288.  
  289.      What has happened is that fred accesses the @_ array which belongs to
  290.      joe.
  291.  
  292.      GGGG____EEEEVVVVAAAALLLL
  293.  
  294.      It is possible for the Perl subroutine you are calling to terminate
  295.      abnormally, e.g., by calling _d_i_e explicitly or by not actually existing.
  296.      By default, when either of these events occurs, the process will
  297.      terminate immediately.  If you want to trap this type of event, specify
  298.      the G_EVAL flag.  It will put an _e_v_a_l { } around the subroutine call.
  299.  
  300.      Whenever control returns from the _p_e_r_l__c_a_l_l_* function you need to check
  301.      the $@ variable as you would in a normal Perl script.
  302.  
  303.      The value returned from the _p_e_r_l__c_a_l_l_* function is dependent on what
  304.      other flags have been specified and whether an error has occurred.  Here
  305.      are all the different cases that can occur:
  306.  
  307.      +o    If the _p_e_r_l__c_a_l_l_* function returns normally, then the value
  308.           returned is as specified in the previous sections.
  309.  
  310.      +o    If G_DISCARD is specified, the return value will always be 0.
  311.  
  312.      +o    If G_ARRAY is specified _a_n_d an error has occurred, the return value
  313.           will always be 0.
  314.  
  315.      +o    If G_SCALAR is specified _a_n_d an error has occurred, the return value
  316.           will be 1 and the value on the top of the stack will be _u_n_d_e_f. This
  317.           means that if you have already detected the error by checking $@ and
  318.           you want the program to continue, you must remember to pop the _u_n_d_e_f
  319.           from the stack.
  320.  
  321.      See _U_s_i_n_g _G__E_V_A_L for details on using G_EVAL.
  322.  
  323.  
  324.  
  325.  
  326.  
  327.                                                                         PPPPaaaaggggeeee 5555
  328.  
  329.  
  330.  
  331.  
  332.  
  333.  
  334. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  335.  
  336.  
  337.  
  338.      GGGG____KKKKEEEEEEEEPPPPEEEERRRRRRRR
  339.  
  340.      You may have noticed that using the G_EVAL flag described above will
  341.      aaaallllwwwwaaaayyyyssss clear the $@ variable and set it to a string describing the error
  342.      iff there was an error in the called code.  This unqualified resetting of
  343.      $@ can be problematic in the reliable identification of errors using the
  344.      eval {} mechanism, because the possibility exists that perl will call
  345.      other code (end of block processing code, for example) between the time
  346.      the error causes $@ to be set within eval {}, and the subsequent
  347.      statement which checks for the value of $@ gets executed in the user's
  348.      script.
  349.  
  350.      This scenario will mostly be applicable to code that is meant to be
  351.      called from within destructors, asynchronous callbacks, signal handlers,
  352.      __DIE__ or __WARN__ hooks, and tie functions.  In such situations, you
  353.      will not want to clear $@ at all, but simply to append any new errors to
  354.      any existing value of $@.
  355.  
  356.      The G_KEEPERR flag is meant to be used in conjunction with G_EVAL in
  357.      _p_e_r_l__c_a_l_l_* functions that are used to implement such code.  This flag
  358.      has no effect when G_EVAL is not used.
  359.  
  360.      When G_KEEPERR is used, any errors in the called code will be prefixed
  361.      with the string "\_t(in cleanup)", and appended to the current value of
  362.      $@.
  363.  
  364.      The G_KEEPERR flag was introduced in Perl version 5.002.
  365.  
  366.      See _U_s_i_n_g _G__K_E_E_P_E_R_R for an example of a situation that warrants the use
  367.      of this flag.
  368.  
  369.      DDDDeeeetttteeeerrrrmmmmiiiinnnniiiinnnngggg tttthhhheeee CCCCoooonnnntttteeeexxxxtttt
  370.  
  371.      As mentioned above, you can determine the context of the currently
  372.      executing subroutine in Perl with _w_a_n_t_a_r_r_a_y.  The equivalent test can be
  373.      made in C by using the GIMME_V macro, which returns G_ARRAY if you have
  374.      been called in an array context, G_SCALAR if in a scalar context, or
  375.      G_VOID if in a void context (i.e. the return value will not be used).  An
  376.      older version of this macro is called GIMME; in a void context it returns
  377.      G_SCALAR instead of G_VOID.  An example of using the GIMME_V macro is
  378.      shown in section _U_s_i_n_g _G_I_M_M_E__V.
  379.  
  380. KKKKNNNNOOOOWWWWNNNN PPPPRRRROOOOBBBBLLLLEEEEMMMMSSSS
  381.      This section outlines all known problems that exist in the _p_e_r_l__c_a_l_l_*
  382.      functions.
  383.  
  384.      1.   If you are intending to make use of both the G_EVAL and G_SCALAR
  385.           flags in your code, use a version of Perl greater than 5.000.  There
  386.           is a bug in version 5.000 of Perl which means that the combination
  387.           of these two flags will not work as described in the section _F_L_A_G
  388.           _V_A_L_U_E_S.
  389.  
  390.  
  391.  
  392.  
  393.                                                                         PPPPaaaaggggeeee 6666
  394.  
  395.  
  396.  
  397.  
  398.  
  399.  
  400. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  401.  
  402.  
  403.  
  404.           Specifically, if the two flags are used when calling a subroutine
  405.           and that subroutine does not call _d_i_e, the value returned by
  406.           _p_e_r_l__c_a_l_l_* will be wrong.
  407.  
  408.      2.   In Perl 5.000 and 5.001 there is a problem with using _p_e_r_l__c_a_l_l_* if
  409.           the Perl sub you are calling attempts to trap a _d_i_e.
  410.  
  411.           The symptom of this problem is that the called Perl sub will
  412.           continue to completion, but whenever it attempts to pass control
  413.           back to the XSUB, the program will immediately terminate.
  414.  
  415.           For example, say you want to call this Perl sub
  416.  
  417.               sub fred
  418.               {
  419.                   eval { die "Fatal Error" ; }
  420.                   print "Trapped error: $@\n"
  421.                       if $@ ;
  422.               }
  423.  
  424.           via this XSUB
  425.  
  426.               void
  427.               Call_fred()
  428.                   CODE:
  429.                   PUSHMARK(SP) ;
  430.                   perl_call_pv("fred", G_DISCARD|G_NOARGS) ;
  431.                   fprintf(stderr, "back in Call_fred\n") ;
  432.  
  433.           When Call_fred is executed it will print
  434.  
  435.               Trapped error: Fatal Error
  436.  
  437.           As control never returns to Call_fred, the "back in Call_fred"
  438.           string will not get printed.
  439.  
  440.           To work around this problem, you can either upgrade to Perl 5.002 or
  441.           higher, or use the G_EVAL flag with _p_e_r_l__c_a_l_l_* as shown below
  442.  
  443.               void
  444.               Call_fred()
  445.                   CODE:
  446.                   PUSHMARK(SP) ;
  447.                   perl_call_pv("fred", G_EVAL|G_DISCARD|G_NOARGS) ;
  448.                   fprintf(stderr, "back in Call_fred\n") ;
  449.  
  450.  
  451. EEEEXXXXAAAAMMMMPPPPLLLLEEEESSSS
  452.      Enough of the definition talk, let's have a few examples.
  453.  
  454.  
  455.  
  456.  
  457.  
  458.  
  459.                                                                         PPPPaaaaggggeeee 7777
  460.  
  461.  
  462.  
  463.  
  464.  
  465.  
  466. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  467.  
  468.  
  469.  
  470.      Perl provides many macros to assist in accessing the Perl stack.
  471.      Wherever possible, these macros should always be used when interfacing to
  472.      Perl internals.  We hope this should make the code less vulnerable to any
  473.      changes made to Perl in the future.
  474.  
  475.      Another point worth noting is that in the first series of examples I have
  476.      made use of only the _p_e_r_l__c_a_l_l__p_v function.  This has been done to keep
  477.      the code simpler and ease you into the topic.  Wherever possible, if the
  478.      choice is between using _p_e_r_l__c_a_l_l__p_v and _p_e_r_l__c_a_l_l__s_v, you should always
  479.      try to use _p_e_r_l__c_a_l_l__s_v.  See _U_s_i_n_g _p_e_r_l__c_a_l_l__s_v for details.
  480.  
  481.      NNNNoooo PPPPaaaarrrraaaammmmeeeetttteeeerrrrssss,,,, NNNNooootttthhhhiiiinnnngggg rrrreeeettttuuuurrrrnnnneeeedddd
  482.  
  483.      This first trivial example will call a Perl subroutine, _P_r_i_n_t_U_I_D, to
  484.      print out the UID of the process.
  485.  
  486.          sub PrintUID
  487.          {
  488.              print "UID is $<\n" ;
  489.          }
  490.  
  491.      and here is a C function to call it
  492.  
  493.          static void
  494.          call_PrintUID()
  495.          {
  496.              dSP ;
  497.  
  498.              PUSHMARK(SP) ;
  499.              perl_call_pv("PrintUID", G_DISCARD|G_NOARGS) ;
  500.          }
  501.  
  502.      Simple, eh.
  503.  
  504.      A few points to note about this example.
  505.  
  506.      1.   Ignore dSP and PUSHMARK(SP) for now. They will be discussed in the
  507.           next example.
  508.  
  509.      2.   We aren't passing any parameters to _P_r_i_n_t_U_I_D so G_NOARGS can be
  510.           specified.
  511.  
  512.      3.   We aren't interested in anything returned from _P_r_i_n_t_U_I_D, so
  513.           G_DISCARD is specified. Even if _P_r_i_n_t_U_I_D was changed to return some
  514.           _v_a_l_u_e(s), having specified G_DISCARD will mean that they will be
  515.           wiped by the time control returns from _p_e_r_l__c_a_l_l__p_v.
  516.  
  517.      4.   As _p_e_r_l__c_a_l_l__p_v is being used, the Perl subroutine is specified as a
  518.           C string. In this case the subroutine name has been 'hard-wired'
  519.           into the code.
  520.  
  521.  
  522.  
  523.  
  524.  
  525.                                                                         PPPPaaaaggggeeee 8888
  526.  
  527.  
  528.  
  529.  
  530.  
  531.  
  532. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  533.  
  534.  
  535.  
  536.      5.   Because we specified G_DISCARD, it is not necessary to check the
  537.           value returned from _p_e_r_l__c_a_l_l__p_v. It will always be 0.
  538.  
  539.      PPPPaaaassssssssiiiinnnngggg PPPPaaaarrrraaaammmmeeeetttteeeerrrrssss
  540.  
  541.      Now let's make a slightly more complex example. This time we want to call
  542.      a Perl subroutine, LeftString, which will take 2 parameters - a string
  543.      ($s) and an integer ($n).  The subroutine will simply print the first $n
  544.      characters of the string.
  545.  
  546.      So the Perl subroutine would look like this
  547.  
  548.          sub LeftString
  549.          {
  550.              my($s, $n) = @_ ;
  551.              print substr($s, 0, $n), "\n" ;
  552.          }
  553.  
  554.      The C function required to call _L_e_f_t_S_t_r_i_n_g would look like this.
  555.  
  556.          static void
  557.          call_LeftString(a, b)
  558.          char * a ;
  559.          int b ;
  560.          {
  561.              dSP ;
  562.  
  563.              ENTER ;
  564.              SAVETMPS ;
  565.  
  566.              PUSHMARK(SP) ;
  567.              XPUSHs(sv_2mortal(newSVpv(a, 0)));
  568.              XPUSHs(sv_2mortal(newSViv(b)));
  569.              PUTBACK ;
  570.  
  571.              perl_call_pv("LeftString", G_DISCARD);
  572.  
  573.              FREETMPS ;
  574.              LEAVE ;
  575.          }
  576.  
  577.      Here are a few notes on the C function _c_a_l_l__L_e_f_t_S_t_r_i_n_g.
  578.  
  579.      1.   Parameters are passed to the Perl subroutine using the Perl stack.
  580.           This is the purpose of the code beginning with the line dSP and
  581.           ending with the line PUTBACK.  The dSP declares a local copy of the
  582.           stack pointer.  This local copy should aaaallllwwwwaaaayyyyssss be accessed as SP.
  583.  
  584.      2.   If you are going to put something onto the Perl stack, you need to
  585.           know where to put it. This is the purpose of the macro dSP - it
  586.           declares and initializes a _l_o_c_a_l copy of the Perl stack pointer.
  587.  
  588.  
  589.  
  590.  
  591.                                                                         PPPPaaaaggggeeee 9999
  592.  
  593.  
  594.  
  595.  
  596.  
  597.  
  598. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  599.  
  600.  
  601.  
  602.           All the other macros which will be used in this example require you
  603.           to have used this macro.
  604.  
  605.           The exception to this rule is if you are calling a Perl subroutine
  606.           directly from an XSUB function. In this case it is not necessary to
  607.           use the dSP macro explicitly - it will be declared for you
  608.           automatically.
  609.  
  610.      3.   Any parameters to be pushed onto the stack should be bracketed by
  611.           the PUSHMARK and PUTBACK macros.  The purpose of these two macros,
  612.           in this context, is to count the number of parameters you are
  613.           pushing automatically.  Then whenever Perl is creating the @_ array
  614.           for the subroutine, it knows how big to make it.
  615.  
  616.           The PUSHMARK macro tells Perl to make a mental note of the current
  617.           stack pointer. Even if you aren't passing any parameters (like the
  618.           example shown in the section _N_o _P_a_r_a_m_e_t_e_r_s, _N_o_t_h_i_n_g _r_e_t_u_r_n_e_d) you
  619.           must still call the PUSHMARK macro before you can call any of the
  620.           _p_e_r_l__c_a_l_l_* functions - Perl still needs to know that there are no
  621.           parameters.
  622.  
  623.           The PUTBACK macro sets the global copy of the stack pointer to be
  624.           the same as our local copy. If we didn't do this _p_e_r_l__c_a_l_l__p_v
  625.           wouldn't know where the two parameters we pushed were - remember
  626.           that up to now all the stack pointer manipulation we have done is
  627.           with our local copy, _n_o_t the global copy.
  628.  
  629.      4.   The only flag specified this time is G_DISCARD. Because we are
  630.           passing 2 parameters to the Perl subroutine this time, we have not
  631.           specified G_NOARGS.
  632.  
  633.      5.   Next, we come to XPUSHs. This is where the parameters actually get
  634.           pushed onto the stack. In this case we are pushing a string and an
  635.           integer.
  636.  
  637.           See the section on _X_S_U_B_s _a_n_d _t_h_e _A_r_g_u_m_e_n_t _S_t_a_c_k in the _p_e_r_l_g_u_t_s
  638.           manpage for details on how the XPUSH macros work.
  639.  
  640.      6.   Because we created temporary values (by means of _s_v__2_m_o_r_t_a_l() calls)
  641.           we will have to tidy up the Perl stack and dispose of mortal SVs.
  642.  
  643.           This is the purpose of
  644.  
  645.               ENTER ;
  646.               SAVETMPS ;
  647.  
  648.           at the start of the function, and
  649.  
  650.               FREETMPS ;
  651.               LEAVE ;
  652.  
  653.           at the end. The ENTER/SAVETMPS pair creates a boundary for any
  654.  
  655.  
  656.  
  657.                                                                        PPPPaaaaggggeeee 11110000
  658.  
  659.  
  660.  
  661.  
  662.  
  663.  
  664. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  665.  
  666.  
  667.  
  668.           temporaries we create.  This means that the temporaries we get rid
  669.           of will be limited to those which were created after these calls.
  670.  
  671.           The FREETMPS/LEAVE pair will get rid of any values returned by the
  672.           Perl subroutine (see next example), plus it will also dump the
  673.           mortal SVs we have created.  Having ENTER/SAVETMPS at the beginning
  674.           of the code makes sure that no other mortals are destroyed.
  675.  
  676.           Think of these macros as working a bit like using { and } in Perl to
  677.           limit the scope of local variables.
  678.  
  679.           See the section _U_s_i_n_g _P_e_r_l _t_o _d_i_s_p_o_s_e _o_f _t_e_m_p_o_r_a_r_i_e_s for details of
  680.           an alternative to using these macros.
  681.  
  682.      7.   Finally, _L_e_f_t_S_t_r_i_n_g can now be called via the _p_e_r_l__c_a_l_l__p_v function.
  683.  
  684.      RRRReeeettttuuuurrrrnnnniiiinnnngggg aaaa SSSSccccaaaallllaaaarrrr
  685.  
  686.      Now for an example of dealing with the items returned from a Perl
  687.      subroutine.
  688.  
  689.      Here is a Perl subroutine, _A_d_d_e_r, that takes 2 integer parameters and
  690.      simply returns their sum.
  691.  
  692.          sub Adder
  693.          {
  694.              my($a, $b) = @_ ;
  695.              $a + $b ;
  696.          }
  697.  
  698.      Because we are now concerned with the return value from _A_d_d_e_r, the C
  699.      function required to call it is now a bit more complex.
  700.  
  701.          static void
  702.          call_Adder(a, b)
  703.          int a ;
  704.          int b ;
  705.          {
  706.              dSP ;
  707.              int count ;
  708.  
  709.              ENTER ;
  710.              SAVETMPS;
  711.  
  712.              PUSHMARK(SP) ;
  713.              XPUSHs(sv_2mortal(newSViv(a)));
  714.              XPUSHs(sv_2mortal(newSViv(b)));
  715.              PUTBACK ;
  716.  
  717.              count = perl_call_pv("Adder", G_SCALAR);
  718.  
  719.              SPAGAIN ;
  720.  
  721.  
  722.  
  723.                                                                        PPPPaaaaggggeeee 11111111
  724.  
  725.  
  726.  
  727.  
  728.  
  729.  
  730. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  731.  
  732.  
  733.  
  734.              if (count != 1)
  735.                  croak("Big trouble\n") ;
  736.  
  737.              printf ("The sum of %d and %d is %d\n", a, b, POPi) ;
  738.  
  739.              PUTBACK ;
  740.              FREETMPS ;
  741.              LEAVE ;
  742.          }
  743.  
  744.      Points to note this time are
  745.  
  746.      1.   The only flag specified this time was G_SCALAR. That means the @_
  747.           array will be created and that the value returned by _A_d_d_e_r will
  748.           still exist after the call to _p_e_r_l__c_a_l_l__p_v.
  749.  
  750.      2.   The purpose of the macro SPAGAIN is to refresh the local copy of the
  751.           stack pointer. This is necessary because it is possible that the
  752.           memory allocated to the Perl stack has been reallocated whilst in
  753.           the _p_e_r_l__c_a_l_l__p_v call.
  754.  
  755.           If you are making use of the Perl stack pointer in your code you
  756.           must always refresh the local copy using SPAGAIN whenever you make
  757.           use of the _p_e_r_l__c_a_l_l_* functions or any other Perl internal
  758.           function.
  759.  
  760.      3.   Although only a single value was expected to be returned from _A_d_d_e_r,
  761.           it is still good practice to check the return code from _p_e_r_l__c_a_l_l__p_v
  762.           anyway.
  763.  
  764.           Expecting a single value is not quite the same as knowing that there
  765.           will be one. If someone modified _A_d_d_e_r to return a list and we
  766.           didn't check for that possibility and take appropriate action the
  767.           Perl stack would end up in an inconsistent state. That is something
  768.           you _r_e_a_l_l_y don't want to happen ever.
  769.  
  770.      4.   The POPi macro is used here to pop the return value from the stack.
  771.           In this case we wanted an integer, so POPi was used.
  772.  
  773.           Here is the complete list of POP macros available, along with the
  774.           types they return.
  775.  
  776.               POPs        SV
  777.               POPp        pointer
  778.               POPn        double
  779.               POPi        integer
  780.               POPl        long
  781.  
  782.  
  783.      5.   The final PUTBACK is used to leave the Perl stack in a consistent
  784.           state before exiting the function.  This is necessary because when
  785.           we popped the return value from the stack with POPi it updated only
  786.  
  787.  
  788.  
  789.                                                                        PPPPaaaaggggeeee 11112222
  790.  
  791.  
  792.  
  793.  
  794.  
  795.  
  796. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  797.  
  798.  
  799.  
  800.           our local copy of the stack pointer.  Remember, PUTBACK sets the
  801.           global stack pointer to be the same as our local copy.
  802.  
  803.      RRRReeeettttuuuurrrrnnnniiiinnnngggg aaaa lllliiiisssstttt ooooffff vvvvaaaalllluuuueeeessss
  804.  
  805.      Now, let's extend the previous example to return both the sum of the
  806.      parameters and the difference.
  807.  
  808.      Here is the Perl subroutine
  809.  
  810.          sub AddSubtract
  811.          {
  812.             my($a, $b) = @_ ;
  813.             ($a+$b, $a-$b) ;
  814.          }
  815.  
  816.      and this is the C function
  817.  
  818.          static void
  819.          call_AddSubtract(a, b)
  820.          int a ;
  821.          int b ;
  822.          {
  823.              dSP ;
  824.              int count ;
  825.  
  826.              ENTER ;
  827.              SAVETMPS;
  828.  
  829.              PUSHMARK(SP) ;
  830.              XPUSHs(sv_2mortal(newSViv(a)));
  831.              XPUSHs(sv_2mortal(newSViv(b)));
  832.              PUTBACK ;
  833.  
  834.              count = perl_call_pv("AddSubtract", G_ARRAY);
  835.  
  836.              SPAGAIN ;
  837.  
  838.              if (count != 2)
  839.                  croak("Big trouble\n") ;
  840.  
  841.              printf ("%d - %d = %d\n", a, b, POPi) ;
  842.              printf ("%d + %d = %d\n", a, b, POPi) ;
  843.  
  844.              PUTBACK ;
  845.              FREETMPS ;
  846.              LEAVE ;
  847.          }
  848.  
  849.      If _c_a_l_l__A_d_d_S_u_b_t_r_a_c_t is called like this
  850.  
  851.  
  852.  
  853.  
  854.  
  855.                                                                        PPPPaaaaggggeeee 11113333
  856.  
  857.  
  858.  
  859.  
  860.  
  861.  
  862. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  863.  
  864.  
  865.  
  866.          call_AddSubtract(7, 4) ;
  867.  
  868.      then here is the output
  869.  
  870.          7 - 4 = 3
  871.          7 + 4 = 11
  872.  
  873.      Notes
  874.  
  875.      1.   We wanted array context, so G_ARRAY was used.
  876.  
  877.      2.   Not surprisingly POPi is used twice this time because we were
  878.           retrieving 2 values from the stack. The important thing to note is
  879.           that when using the POP* macros they come off the stack in _r_e_v_e_r_s_e
  880.           order.
  881.  
  882.      RRRReeeettttuuuurrrrnnnniiiinnnngggg aaaa lllliiiisssstttt iiiinnnn aaaa ssssccccaaaallllaaaarrrr ccccoooonnnntttteeeexxxxtttt
  883.  
  884.      Say the Perl subroutine in the previous section was called in a scalar
  885.      context, like this
  886.  
  887.          static void
  888.          call_AddSubScalar(a, b)
  889.          int a ;
  890.          int b ;
  891.          {
  892.              dSP ;
  893.              int count ;
  894.              int i ;
  895.  
  896.              ENTER ;
  897.              SAVETMPS;
  898.  
  899.              PUSHMARK(SP) ;
  900.              XPUSHs(sv_2mortal(newSViv(a)));
  901.              XPUSHs(sv_2mortal(newSViv(b)));
  902.              PUTBACK ;
  903.  
  904.              count = perl_call_pv("AddSubtract", G_SCALAR);
  905.  
  906.              SPAGAIN ;
  907.  
  908.              printf ("Items Returned = %d\n", count) ;
  909.  
  910.              for (i = 1 ; i <= count ; ++i)
  911.                  printf ("Value %d = %d\n", i, POPi) ;
  912.  
  913.              PUTBACK ;
  914.              FREETMPS ;
  915.              LEAVE ;
  916.          }
  917.  
  918.  
  919.  
  920.  
  921.                                                                        PPPPaaaaggggeeee 11114444
  922.  
  923.  
  924.  
  925.  
  926.  
  927.  
  928. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  929.  
  930.  
  931.  
  932.      The other modification made is that _c_a_l_l__A_d_d_S_u_b_S_c_a_l_a_r will print the
  933.      number of items returned from the Perl subroutine and their value (for
  934.      simplicity it assumes that they are integer).  So if _c_a_l_l__A_d_d_S_u_b_S_c_a_l_a_r is
  935.      called
  936.  
  937.          call_AddSubScalar(7, 4) ;
  938.  
  939.      then the output will be
  940.  
  941.          Items Returned = 1
  942.          Value 1 = 3
  943.  
  944.      In this case the main point to note is that only the last item in the
  945.      list is returned from the subroutine, _A_d_d_S_u_b_t_r_a_c_t actually made it back
  946.      to _c_a_l_l__A_d_d_S_u_b_S_c_a_l_a_r.
  947.  
  948.      RRRReeeettttuuuurrrrnnnniiiinnnngggg DDDDaaaattttaaaa ffffrrrroooommmm PPPPeeeerrrrllll vvvviiiiaaaa tttthhhheeee ppppaaaarrrraaaammmmeeeetttteeeerrrr lllliiiisssstttt
  949.  
  950.      It is also possible to return values directly via the parameter list -
  951.      whether it is actually desirable to do it is another matter entirely.
  952.  
  953.      The Perl subroutine, _I_n_c, below takes 2 parameters and increments each
  954.      directly.
  955.  
  956.          sub Inc
  957.          {
  958.              ++ $_[0] ;
  959.              ++ $_[1] ;
  960.          }
  961.  
  962.      and here is a C function to call it.
  963.  
  964.          static void
  965.          call_Inc(a, b)
  966.          int a ;
  967.          int b ;
  968.          {
  969.              dSP ;
  970.              int count ;
  971.              SV * sva ;
  972.              SV * svb ;
  973.  
  974.              ENTER ;
  975.              SAVETMPS;
  976.  
  977.              sva = sv_2mortal(newSViv(a)) ;
  978.              svb = sv_2mortal(newSViv(b)) ;
  979.  
  980.              PUSHMARK(SP) ;
  981.              XPUSHs(sva);
  982.              XPUSHs(svb);
  983.              PUTBACK ;
  984.  
  985.  
  986.  
  987.                                                                        PPPPaaaaggggeeee 11115555
  988.  
  989.  
  990.  
  991.  
  992.  
  993.  
  994. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  995.  
  996.  
  997.  
  998.              count = perl_call_pv("Inc", G_DISCARD);
  999.  
  1000.              if (count != 0)
  1001.                  croak ("call_Inc: expected 0 values from 'Inc', got %d\n",
  1002.                         count) ;
  1003.  
  1004.              printf ("%d + 1 = %d\n", a, SvIV(sva)) ;
  1005.              printf ("%d + 1 = %d\n", b, SvIV(svb)) ;
  1006.  
  1007.              FREETMPS ;
  1008.              LEAVE ;
  1009.          }
  1010.  
  1011.      To be able to access the two parameters that were pushed onto the stack
  1012.      after they return from _p_e_r_l__c_a_l_l__p_v it is necessary to make a note of
  1013.      their addresses - thus the two variables sva and svb.
  1014.  
  1015.      The reason this is necessary is that the area of the Perl stack which
  1016.      held them will very likely have been overwritten by something else by the
  1017.      time control returns from _p_e_r_l__c_a_l_l__p_v.
  1018.  
  1019.      UUUUssssiiiinnnngggg GGGG____EEEEVVVVAAAALLLL
  1020.  
  1021.      Now an example using G_EVAL. Below is a Perl subroutine which computes
  1022.      the difference of its 2 parameters. If this would result in a negative
  1023.      result, the subroutine calls _d_i_e.
  1024.  
  1025.          sub Subtract
  1026.          {
  1027.              my ($a, $b) = @_ ;
  1028.  
  1029.              die "death can be fatal\n" if $a < $b ;
  1030.  
  1031.              $a - $b ;
  1032.          }
  1033.  
  1034.      and some C to call it
  1035.  
  1036.          static void
  1037.          call_Subtract(a, b)
  1038.          int a ;
  1039.          int b ;
  1040.          {
  1041.              dSP ;
  1042.              int count ;
  1043.  
  1044.              ENTER ;
  1045.              SAVETMPS;
  1046.  
  1047.  
  1048.  
  1049.  
  1050.  
  1051.  
  1052.  
  1053.                                                                        PPPPaaaaggggeeee 11116666
  1054.  
  1055.  
  1056.  
  1057.  
  1058.  
  1059.  
  1060. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1061.  
  1062.  
  1063.  
  1064.              PUSHMARK(SP) ;
  1065.              XPUSHs(sv_2mortal(newSViv(a)));
  1066.              XPUSHs(sv_2mortal(newSViv(b)));
  1067.              PUTBACK ;
  1068.  
  1069.              count = perl_call_pv("Subtract", G_EVAL|G_SCALAR);
  1070.  
  1071.              SPAGAIN ;
  1072.  
  1073.              /* Check the eval first */
  1074.              if (SvTRUE(ERRSV))
  1075.              {
  1076.                  printf ("Uh oh - %s\n", SvPV(ERRSV, PL_na)) ;
  1077.                  POPs ;
  1078.              }
  1079.              else
  1080.              {
  1081.                  if (count != 1)
  1082.                     croak("call_Subtract: wanted 1 value from 'Subtract', got %d\n",
  1083.                              count) ;
  1084.  
  1085.                  printf ("%d - %d = %d\n", a, b, POPi) ;
  1086.              }
  1087.  
  1088.              PUTBACK ;
  1089.              FREETMPS ;
  1090.              LEAVE ;
  1091.          }
  1092.  
  1093.      If _c_a_l_l__S_u_b_t_r_a_c_t is called thus
  1094.  
  1095.          call_Subtract(4, 5)
  1096.  
  1097.      the following will be printed
  1098.  
  1099.          Uh oh - death can be fatal
  1100.  
  1101.      Notes
  1102.  
  1103.      1.   We want to be able to catch the _d_i_e so we have used the G_EVAL flag.
  1104.           Not specifying this flag would mean that the program would terminate
  1105.           immediately at the _d_i_e statement in the subroutine _S_u_b_t_r_a_c_t.
  1106.  
  1107.      2.   The code
  1108.  
  1109.               if (SvTRUE(ERRSV))
  1110.               {
  1111.                   printf ("Uh oh - %s\n", SvPV(ERRSV, PL_na)) ;
  1112.                   POPs ;
  1113.               }
  1114.  
  1115.           is the direct equivalent of this bit of Perl
  1116.  
  1117.  
  1118.  
  1119.                                                                        PPPPaaaaggggeeee 11117777
  1120.  
  1121.  
  1122.  
  1123.  
  1124.  
  1125.  
  1126. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1127.  
  1128.  
  1129.  
  1130.               print "Uh oh - $@\n" if $@ ;
  1131.  
  1132.           PL_errgv is a perl global of type GV * that points to the symbol
  1133.           table entry containing the error.  ERRSV therefore refers to the C
  1134.           equivalent of $@.
  1135.  
  1136.      3.   Note that the stack is popped using POPs in the block where
  1137.           SvTRUE(ERRSV) is true.  This is necessary because whenever a
  1138.           _p_e_r_l__c_a_l_l_* function invoked with G_EVAL|G_SCALAR returns an error,
  1139.           the top of the stack holds the value _u_n_d_e_f. Because we want the
  1140.           program to continue after detecting this error, it is essential that
  1141.           the stack is tidied up by removing the _u_n_d_e_f.
  1142.  
  1143.      UUUUssssiiiinnnngggg GGGG____KKKKEEEEEEEEPPPPEEEERRRRRRRR
  1144.  
  1145.      Consider this rather facetious example, where we have used an XS version
  1146.      of the call_Subtract example above inside a destructor:
  1147.  
  1148.          package Foo;
  1149.          sub new { bless {}, $_[0] }
  1150.          sub Subtract {
  1151.              my($a,$b) = @_;
  1152.              die "death can be fatal" if $a < $b ;
  1153.              $a - $b;
  1154.          }
  1155.          sub DESTROY { call_Subtract(5, 4); }
  1156.          sub foo { die "foo dies"; }
  1157.  
  1158.          package main;
  1159.          eval { Foo->new->foo };
  1160.          print "Saw: $@" if $@;             # should be, but isn't
  1161.  
  1162.      This example will fail to recognize that an error occurred inside the
  1163.      eval {}.  Here's why: the call_Subtract code got executed while perl was
  1164.      cleaning up temporaries when exiting the eval block, and because
  1165.      call_Subtract is implemented with _p_e_r_l__c_a_l_l__p_v using the G_EVAL flag, it
  1166.      promptly reset $@.  This results in the failure of the outermost test for
  1167.      $@, and thereby the failure of the error trap.
  1168.  
  1169.      Appending the G_KEEPERR flag, so that the _p_e_r_l__c_a_l_l__p_v call in
  1170.      call_Subtract reads:
  1171.  
  1172.              count = perl_call_pv("Subtract", G_EVAL|G_SCALAR|G_KEEPERR);
  1173.  
  1174.      will preserve the error and restore reliable error handling.
  1175.  
  1176.      UUUUssssiiiinnnngggg ppppeeeerrrrllll____ccccaaaallllllll____ssssvvvv
  1177.  
  1178.      In all the previous examples I have 'hard-wired' the name of the Perl
  1179.      subroutine to be called from C.  Most of the time though, it is more
  1180.      convenient to be able to specify the name of the Perl subroutine from
  1181.      within the Perl script.
  1182.  
  1183.  
  1184.  
  1185.                                                                        PPPPaaaaggggeeee 11118888
  1186.  
  1187.  
  1188.  
  1189.  
  1190.  
  1191.  
  1192. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1193.  
  1194.  
  1195.  
  1196.      Consider the Perl code below
  1197.  
  1198.          sub fred
  1199.          {
  1200.              print "Hello there\n" ;
  1201.          }
  1202.  
  1203.          CallSubPV("fred") ;
  1204.  
  1205.      Here is a snippet of XSUB which defines _C_a_l_l_S_u_b_P_V.
  1206.  
  1207.          void
  1208.          CallSubPV(name)
  1209.              char *  name
  1210.              CODE:
  1211.              PUSHMARK(SP) ;
  1212.              perl_call_pv(name, G_DISCARD|G_NOARGS) ;
  1213.  
  1214.      That is fine as far as it goes. The thing is, the Perl subroutine can be
  1215.      specified as only a string.  For Perl 4 this was adequate, but Perl 5
  1216.      allows references to subroutines and anonymous subroutines.  This is
  1217.      where _p_e_r_l__c_a_l_l__s_v is useful.
  1218.  
  1219.      The code below for _C_a_l_l_S_u_b_S_V is identical to _C_a_l_l_S_u_b_P_V except that the
  1220.      name parameter is now defined as an SV* and we use _p_e_r_l__c_a_l_l__s_v instead
  1221.      of _p_e_r_l__c_a_l_l__p_v.
  1222.  
  1223.          void
  1224.          CallSubSV(name)
  1225.              SV *    name
  1226.              CODE:
  1227.              PUSHMARK(SP) ;
  1228.              perl_call_sv(name, G_DISCARD|G_NOARGS) ;
  1229.  
  1230.      Because we are using an SV to call _f_r_e_d the following can all be used
  1231.  
  1232.          CallSubSV("fred") ;
  1233.          CallSubSV(\&fred) ;
  1234.          $ref = \&fred ;
  1235.          CallSubSV($ref) ;
  1236.          CallSubSV( sub { print "Hello there\n" } ) ;
  1237.  
  1238.      As you can see, _p_e_r_l__c_a_l_l__s_v gives you much greater flexibility in how
  1239.      you can specify the Perl subroutine.
  1240.  
  1241.      You should note that if it is necessary to store the SV (name in the
  1242.      example above) which corresponds to the Perl subroutine so that it can be
  1243.      used later in the program, it not enough just to store a copy of the
  1244.      pointer to the SV. Say the code above had been like this
  1245.  
  1246.  
  1247.  
  1248.  
  1249.  
  1250.  
  1251.                                                                        PPPPaaaaggggeeee 11119999
  1252.  
  1253.  
  1254.  
  1255.  
  1256.  
  1257.  
  1258. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1259.  
  1260.  
  1261.  
  1262.          static SV * rememberSub ;
  1263.  
  1264.          void
  1265.          SaveSub1(name)
  1266.              SV *    name
  1267.              CODE:
  1268.              rememberSub = name ;
  1269.  
  1270.          void
  1271.          CallSavedSub1()
  1272.              CODE:
  1273.              PUSHMARK(SP) ;
  1274.              perl_call_sv(rememberSub, G_DISCARD|G_NOARGS) ;
  1275.  
  1276.      The reason this is wrong is that by the time you come to use the pointer
  1277.      rememberSub in CallSavedSub1, it may or may not still refer to the Perl
  1278.      subroutine that was recorded in SaveSub1.  This is particularly true for
  1279.      these cases
  1280.  
  1281.          SaveSub1(\&fred) ;
  1282.          CallSavedSub1() ;
  1283.  
  1284.          SaveSub1( sub { print "Hello there\n" } ) ;
  1285.          CallSavedSub1() ;
  1286.  
  1287.      By the time each of the SaveSub1 statements above have been executed, the
  1288.      SV*s which corresponded to the parameters will no longer exist.  Expect
  1289.      an error message from Perl of the form
  1290.  
  1291.          Can't use an undefined value as a subroutine reference at ...
  1292.  
  1293.      for each of the CallSavedSub1 lines.
  1294.  
  1295.      Similarly, with this code
  1296.  
  1297.          $ref = \&fred ;
  1298.          SaveSub1($ref) ;
  1299.          $ref = 47 ;
  1300.          CallSavedSub1() ;
  1301.  
  1302.      you can expect one of these messages (which you actually get is dependent
  1303.      on the version of Perl you are using)
  1304.  
  1305.          Not a CODE reference at ...
  1306.          Undefined subroutine &main::47 called ...
  1307.  
  1308.      The variable $ref may have referred to the subroutine fred whenever the
  1309.      call to SaveSub1 was made but by the time CallSavedSub1 gets called it
  1310.      now holds the number 47. Because we saved only a pointer to the original
  1311.      SV in SaveSub1, any changes to $ref will be tracked by the pointer
  1312.      rememberSub. This means that whenever CallSavedSub1 gets called, it will
  1313.      attempt to execute the code which is referenced by the SV* rememberSub.
  1314.  
  1315.  
  1316.  
  1317.                                                                        PPPPaaaaggggeeee 22220000
  1318.  
  1319.  
  1320.  
  1321.  
  1322.  
  1323.  
  1324. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1325.  
  1326.  
  1327.  
  1328.      In this case though, it now refers to the integer 47, so expect Perl to
  1329.      complain loudly.
  1330.  
  1331.      A similar but more subtle problem is illustrated with this code
  1332.  
  1333.          $ref = \&fred ;
  1334.          SaveSub1($ref) ;
  1335.          $ref = \&joe ;
  1336.          CallSavedSub1() ;
  1337.  
  1338.      This time whenever CallSavedSub1 get called it will execute the Perl
  1339.      subroutine joe (assuming it exists) rather than fred as was originally
  1340.      requested in the call to SaveSub1.
  1341.  
  1342.      To get around these problems it is necessary to take a full copy of the
  1343.      SV.  The code below shows SaveSub2 modified to do that
  1344.  
  1345.          static SV * keepSub = (SV*)NULL ;
  1346.  
  1347.          void
  1348.          SaveSub2(name)
  1349.              SV *    name
  1350.              CODE:
  1351.              /* Take a copy of the callback */
  1352.              if (keepSub == (SV*)NULL)
  1353.                  /* First time, so create a new SV */
  1354.                  keepSub = newSVsv(name) ;
  1355.              else
  1356.                  /* Been here before, so overwrite */
  1357.                  SvSetSV(keepSub, name) ;
  1358.  
  1359.          void
  1360.          CallSavedSub2()
  1361.              CODE:
  1362.              PUSHMARK(SP) ;
  1363.              perl_call_sv(keepSub, G_DISCARD|G_NOARGS) ;
  1364.  
  1365.      To avoid creating a new SV every time SaveSub2 is called, the function
  1366.      first checks to see if it has been called before.  If not, then space for
  1367.      a new SV is allocated and the reference to the Perl subroutine, name is
  1368.      copied to the variable keepSub in one operation using newSVsv.
  1369.      Thereafter, whenever SaveSub2 is called the existing SV, keepSub, is
  1370.      overwritten with the new value using SvSetSV.
  1371.  
  1372.      UUUUssssiiiinnnngggg ppppeeeerrrrllll____ccccaaaallllllll____aaaarrrrggggvvvv
  1373.  
  1374.      Here is a Perl subroutine which prints whatever parameters are passed to
  1375.      it.
  1376.  
  1377.          sub PrintList
  1378.          {
  1379.              my(@list) = @_ ;
  1380.  
  1381.  
  1382.  
  1383.                                                                        PPPPaaaaggggeeee 22221111
  1384.  
  1385.  
  1386.  
  1387.  
  1388.  
  1389.  
  1390. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1391.  
  1392.  
  1393.  
  1394.              foreach (@list) { print "$_\n" }
  1395.          }
  1396.  
  1397.      and here is an example of _p_e_r_l__c_a_l_l__a_r_g_v which will call _P_r_i_n_t_L_i_s_t.
  1398.  
  1399.          static char * words[] = {"alpha", "beta", "gamma", "delta", NULL} ;
  1400.  
  1401.          static void
  1402.          call_PrintList()
  1403.          {
  1404.              dSP ;
  1405.  
  1406.              perl_call_argv("PrintList", G_DISCARD, words) ;
  1407.          }
  1408.  
  1409.      Note that it is not necessary to call PUSHMARK in this instance.  This is
  1410.      because _p_e_r_l__c_a_l_l__a_r_g_v will do it for you.
  1411.  
  1412.      UUUUssssiiiinnnngggg ppppeeeerrrrllll____ccccaaaallllllll____mmmmeeeetttthhhhoooodddd
  1413.  
  1414.      Consider the following Perl code
  1415.  
  1416.          {
  1417.              package Mine ;
  1418.  
  1419.              sub new
  1420.              {
  1421.                  my($type) = shift ;
  1422.                  bless [@_]
  1423.              }
  1424.  
  1425.              sub Display
  1426.              {
  1427.                  my ($self, $index) = @_ ;
  1428.                  print "$index: $$self[$index]\n" ;
  1429.              }
  1430.  
  1431.              sub PrintID
  1432.              {
  1433.                  my($class) = @_ ;
  1434.                  print "This is Class $class version 1.0\n" ;
  1435.              }
  1436.          }
  1437.  
  1438.      It implements just a very simple class to manage an array.  Apart from
  1439.      the constructor, new, it declares methods, one static and one virtual.
  1440.      The static method, PrintID, prints out simply the class name and a
  1441.      version number. The virtual method, Display, prints out a single element
  1442.      of the array.  Here is an all Perl example of using it.
  1443.  
  1444.  
  1445.  
  1446.  
  1447.  
  1448.  
  1449.                                                                        PPPPaaaaggggeeee 22222222
  1450.  
  1451.  
  1452.  
  1453.  
  1454.  
  1455.  
  1456. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1457.  
  1458.  
  1459.  
  1460.          $a = new Mine ('red', 'green', 'blue') ;
  1461.          $a->Display(1) ;
  1462.          PrintID Mine;
  1463.  
  1464.      will print
  1465.  
  1466.          1: green
  1467.          This is Class Mine version 1.0
  1468.  
  1469.      Calling a Perl method from C is fairly straightforward. The following
  1470.      things are required
  1471.  
  1472.      +o    a reference to the object for a virtual method or the name of the
  1473.           class for a static method.
  1474.  
  1475.      +o    the name of the method.
  1476.  
  1477.      +o    any other parameters specific to the method.
  1478.  
  1479.      Here is a simple XSUB which illustrates the mechanics of calling both the
  1480.      PrintID and Display methods from C.
  1481.  
  1482.          void
  1483.          call_Method(ref, method, index)
  1484.              SV *    ref
  1485.              char *  method
  1486.              int             index
  1487.              CODE:
  1488.              PUSHMARK(SP);
  1489.              XPUSHs(ref);
  1490.              XPUSHs(sv_2mortal(newSViv(index))) ;
  1491.              PUTBACK;
  1492.  
  1493.              perl_call_method(method, G_DISCARD) ;
  1494.  
  1495.          void
  1496.          call_PrintID(class, method)
  1497.              char *  class
  1498.              char *  method
  1499.              CODE:
  1500.              PUSHMARK(SP);
  1501.              XPUSHs(sv_2mortal(newSVpv(class, 0))) ;
  1502.              PUTBACK;
  1503.  
  1504.              perl_call_method(method, G_DISCARD) ;
  1505.  
  1506.      So the methods PrintID and Display can be invoked like this
  1507.  
  1508.          $a = new Mine ('red', 'green', 'blue') ;
  1509.          call_Method($a, 'Display', 1) ;
  1510.          call_PrintID('Mine', 'PrintID') ;
  1511.  
  1512.  
  1513.  
  1514.  
  1515.                                                                        PPPPaaaaggggeeee 22223333
  1516.  
  1517.  
  1518.  
  1519.  
  1520.  
  1521.  
  1522. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1523.  
  1524.  
  1525.  
  1526.      The only thing to note is that in both the static and virtual methods,
  1527.      the method name is not passed via the stack - it is used as the first
  1528.      parameter to _p_e_r_l__c_a_l_l__m_e_t_h_o_d.
  1529.  
  1530.      UUUUssssiiiinnnngggg GGGGIIIIMMMMMMMMEEEE____VVVV
  1531.  
  1532.      Here is a trivial XSUB which prints the context in which it is currently
  1533.      executing.
  1534.  
  1535.          void
  1536.          PrintContext()
  1537.              CODE:
  1538.              I32 gimme = GIMME_V;
  1539.              if (gimme == G_VOID)
  1540.                  printf ("Context is Void\n") ;
  1541.              else if (gimme == G_SCALAR)
  1542.                  printf ("Context is Scalar\n") ;
  1543.              else
  1544.                  printf ("Context is Array\n") ;
  1545.  
  1546.      and here is some Perl to test it
  1547.  
  1548.          PrintContext ;
  1549.          $a = PrintContext ;
  1550.          @a = PrintContext ;
  1551.  
  1552.      The output from that will be
  1553.  
  1554.          Context is Void
  1555.          Context is Scalar
  1556.          Context is Array
  1557.  
  1558.  
  1559.      UUUUssssiiiinnnngggg PPPPeeeerrrrllll ttttoooo ddddiiiissssppppoooosssseeee ooooffff tttteeeemmmmppppoooorrrraaaarrrriiiieeeessss
  1560.  
  1561.      In the examples given to date, any temporaries created in the callback
  1562.      (i.e., parameters passed on the stack to the _p_e_r_l__c_a_l_l_* function or
  1563.      values returned via the stack) have been freed by one of these methods
  1564.  
  1565.      +o    specifying the G_DISCARD flag with _p_e_r_l__c_a_l_l_*.
  1566.  
  1567.      +o    explicitly disposed of using the ENTER/SAVETMPS - FREETMPS/LEAVE
  1568.           pairing.
  1569.  
  1570.      There is another method which can be used, namely letting Perl do it for
  1571.      you automatically whenever it regains control after the callback has
  1572.      terminated.  This is done by simply not using the
  1573.  
  1574.  
  1575.  
  1576.  
  1577.  
  1578.  
  1579.  
  1580.  
  1581.                                                                        PPPPaaaaggggeeee 22224444
  1582.  
  1583.  
  1584.  
  1585.  
  1586.  
  1587.  
  1588. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1589.  
  1590.  
  1591.  
  1592.          ENTER ;
  1593.          SAVETMPS ;
  1594.          ...
  1595.          FREETMPS ;
  1596.          LEAVE ;
  1597.  
  1598.      sequence in the callback (and not, of course, specifying the G_DISCARD
  1599.      flag).
  1600.  
  1601.      If you are going to use this method you have to be aware of a possible
  1602.      memory leak which can arise under very specific circumstances.  To
  1603.      explain these circumstances you need to know a bit about the flow of
  1604.      control between Perl and the callback routine.
  1605.  
  1606.      The examples given at the start of the document (an error handler and an
  1607.      event driven program) are typical of the two main sorts of flow control
  1608.      that you are likely to encounter with callbacks.  There is a very
  1609.      important distinction between them, so pay attention.
  1610.  
  1611.      In the first example, an error handler, the flow of control could be as
  1612.      follows.  You have created an interface to an external library.  Control
  1613.      can reach the external library like this
  1614.  
  1615.          perl --> XSUB --> external library
  1616.  
  1617.      Whilst control is in the library, an error condition occurs. You have
  1618.      previously set up a Perl callback to handle this situation, so it will
  1619.      get executed. Once the callback has finished, control will drop back to
  1620.      Perl again.  Here is what the flow of control will be like in that
  1621.      situation
  1622.  
  1623.          perl --> XSUB --> external library
  1624.                            ...
  1625.                            error occurs
  1626.                            ...
  1627.                            external library --> perl_call --> perl
  1628.                                                                |
  1629.          perl <-- XSUB <-- external library <-- perl_call <----+
  1630.  
  1631.      After processing of the error using _p_e_r_l__c_a_l_l_* is completed, control
  1632.      reverts back to Perl more or less immediately.
  1633.  
  1634.      In the diagram, the further right you go the more deeply nested the scope
  1635.      is.  It is only when control is back with perl on the extreme left of the
  1636.      diagram that you will have dropped back to the enclosing scope and any
  1637.      temporaries you have left hanging around will be freed.
  1638.  
  1639.      In the second example, an event driven program, the flow of control will
  1640.      be more like this
  1641.  
  1642.  
  1643.  
  1644.  
  1645.  
  1646.  
  1647.                                                                        PPPPaaaaggggeeee 22225555
  1648.  
  1649.  
  1650.  
  1651.  
  1652.  
  1653.  
  1654. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1655.  
  1656.  
  1657.  
  1658.          perl --> XSUB --> event handler
  1659.                            ...
  1660.                            event handler --> perl_call --> perl
  1661.                                                             |
  1662.                            event handler <-- perl_call <----+
  1663.                            ...
  1664.                            event handler --> perl_call --> perl
  1665.                                                             |
  1666.                            event handler <-- perl_call <----+
  1667.                            ...
  1668.                            event handler --> perl_call --> perl
  1669.                                                             |
  1670.                            event handler <-- perl_call <----+
  1671.  
  1672.      In this case the flow of control can consist of only the repeated
  1673.      sequence
  1674.  
  1675.          event handler --> perl_call --> perl
  1676.  
  1677.      for practically the complete duration of the program.  This means that
  1678.      control may _n_e_v_e_r drop back to the surrounding scope in Perl at the
  1679.      extreme left.
  1680.  
  1681.      So what is the big problem? Well, if you are expecting Perl to tidy up
  1682.      those temporaries for you, you might be in for a long wait.  For Perl to
  1683.      dispose of your temporaries, control must drop back to the enclosing
  1684.      scope at some stage.  In the event driven scenario that may never happen.
  1685.      This means that as time goes on, your program will create more and more
  1686.      temporaries, none of which will ever be freed. As each of these
  1687.      temporaries consumes some memory your program will eventually consume all
  1688.      the available memory in your system - kapow!
  1689.  
  1690.      So here is the bottom line - if you are sure that control will revert
  1691.      back to the enclosing Perl scope fairly quickly after the end of your
  1692.      callback, then it isn't absolutely necessary to dispose explicitly of any
  1693.      temporaries you may have created. Mind you, if you are at all uncertain
  1694.      about what to do, it doesn't do any harm to tidy up anyway.
  1695.  
  1696.      SSSSttttrrrraaaatttteeeeggggiiiieeeessss ffffoooorrrr ssssttttoooorrrriiiinnnngggg CCCCaaaallllllllbbbbaaaacccckkkk CCCCoooonnnntttteeeexxxxtttt IIIInnnnffffoooorrrrmmmmaaaattttiiiioooonnnn
  1697.  
  1698.      Potentially one of the trickiest problems to overcome when designing a
  1699.      callback interface can be figuring out how to store the mapping between
  1700.      the C callback function and the Perl equivalent.
  1701.  
  1702.      To help understand why this can be a real problem first consider how a
  1703.      callback is set up in an all C environment.  Typically a C API will
  1704.      provide a function to register a callback.  This will expect a pointer to
  1705.      a function as one of its parameters.  Below is a call to a hypothetical
  1706.      function register_fatal which registers the C function to get called when
  1707.      a fatal error occurs.
  1708.  
  1709.  
  1710.  
  1711.  
  1712.  
  1713.                                                                        PPPPaaaaggggeeee 22226666
  1714.  
  1715.  
  1716.  
  1717.  
  1718.  
  1719.  
  1720. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1721.  
  1722.  
  1723.  
  1724.          register_fatal(cb1) ;
  1725.  
  1726.      The single parameter cb1 is a pointer to a function, so you must have
  1727.      defined cb1 in your code, say something like this
  1728.  
  1729.          static void
  1730.          cb1()
  1731.          {
  1732.              printf ("Fatal Error\n") ;
  1733.              exit(1) ;
  1734.          }
  1735.  
  1736.      Now change that to call a Perl subroutine instead
  1737.  
  1738.          static SV * callback = (SV*)NULL;
  1739.  
  1740.          static void
  1741.          cb1()
  1742.          {
  1743.              dSP ;
  1744.  
  1745.              PUSHMARK(SP) ;
  1746.  
  1747.              /* Call the Perl sub to process the callback */
  1748.              perl_call_sv(callback, G_DISCARD) ;
  1749.          }
  1750.  
  1751.          void
  1752.          register_fatal(fn)
  1753.              SV *    fn
  1754.              CODE:
  1755.              /* Remember the Perl sub */
  1756.              if (callback == (SV*)NULL)
  1757.                  callback = newSVsv(fn) ;
  1758.              else
  1759.                  SvSetSV(callback, fn) ;
  1760.  
  1761.              /* register the callback with the external library */
  1762.              register_fatal(cb1) ;
  1763.  
  1764.      where the Perl equivalent of register_fatal and the callback it
  1765.      registers, pcb1, might look like this
  1766.  
  1767.          # Register the sub pcb1
  1768.          register_fatal(\&pcb1) ;
  1769.  
  1770.          sub pcb1
  1771.          {
  1772.              die "I'm dying...\n" ;
  1773.          }
  1774.  
  1775.      The mapping between the C callback and the Perl equivalent is stored in
  1776.  
  1777.  
  1778.  
  1779.                                                                        PPPPaaaaggggeeee 22227777
  1780.  
  1781.  
  1782.  
  1783.  
  1784.  
  1785.  
  1786. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1787.  
  1788.  
  1789.  
  1790.      the global variable callback.
  1791.  
  1792.      This will be adequate if you ever need to have only one callback
  1793.      registered at any time. An example could be an error handler like the
  1794.      code sketched out above. Remember though, repeated calls to
  1795.      register_fatal will replace the previously registered callback function
  1796.      with the new one.
  1797.  
  1798.      Say for example you want to interface to a library which allows
  1799.      asynchronous file i/o.  In this case you may be able to register a
  1800.      callback whenever a read operation has completed. To be of any use we
  1801.      want to be able to call separate Perl subroutines for each file that is
  1802.      opened.  As it stands, the error handler example above would not be
  1803.      adequate as it allows only a single callback to be defined at any time.
  1804.      What we require is a means of storing the mapping between the opened file
  1805.      and the Perl subroutine we want to be called for that file.
  1806.  
  1807.      Say the i/o library has a function asynch_read which associates a C
  1808.      function ProcessRead with a file handle fh - this assumes that it has
  1809.      also provided some routine to open the file and so obtain the file
  1810.      handle.
  1811.  
  1812.          asynch_read(fh, ProcessRead)
  1813.  
  1814.      This may expect the C _P_r_o_c_e_s_s_R_e_a_d function of this form
  1815.  
  1816.          void
  1817.          ProcessRead(fh, buffer)
  1818.          int fh ;
  1819.          char *      buffer ;
  1820.          {
  1821.               ...
  1822.          }
  1823.  
  1824.      To provide a Perl interface to this library we need to be able to map
  1825.      between the fh parameter and the Perl subroutine we want called.  A hash
  1826.      is a convenient mechanism for storing this mapping.  The code below shows
  1827.      a possible implementation
  1828.  
  1829.          static HV * Mapping = (HV*)NULL ;
  1830.  
  1831.          void
  1832.          asynch_read(fh, callback)
  1833.              int     fh
  1834.              SV *    callback
  1835.              CODE:
  1836.              /* If the hash doesn't already exist, create it */
  1837.              if (Mapping == (HV*)NULL)
  1838.                  Mapping = newHV() ;
  1839.  
  1840.              /* Save the fh -> callback mapping */
  1841.              hv_store(Mapping, (char*)&fh, sizeof(fh), newSVsv(callback), 0) ;
  1842.  
  1843.  
  1844.  
  1845.                                                                        PPPPaaaaggggeeee 22228888
  1846.  
  1847.  
  1848.  
  1849.  
  1850.  
  1851.  
  1852. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1853.  
  1854.  
  1855.  
  1856.              /* Register with the C Library */
  1857.              asynch_read(fh, asynch_read_if) ;
  1858.  
  1859.      and asynch_read_if could look like this
  1860.  
  1861.          static void
  1862.          asynch_read_if(fh, buffer)
  1863.          int fh ;
  1864.          char *      buffer ;
  1865.          {
  1866.              dSP ;
  1867.              SV ** sv ;
  1868.  
  1869.              /* Get the callback associated with fh */
  1870.              sv =  hv_fetch(Mapping, (char*)&fh , sizeof(fh), FALSE) ;
  1871.              if (sv == (SV**)NULL)
  1872.                  croak("Internal error...\n") ;
  1873.  
  1874.              PUSHMARK(SP) ;
  1875.              XPUSHs(sv_2mortal(newSViv(fh))) ;
  1876.              XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  1877.              PUTBACK ;
  1878.  
  1879.              /* Call the Perl sub */
  1880.              perl_call_sv(*sv, G_DISCARD) ;
  1881.          }
  1882.  
  1883.      For completeness, here is asynch_close.  This shows how to remove the
  1884.      entry from the hash Mapping.
  1885.  
  1886.          void
  1887.          asynch_close(fh)
  1888.              int     fh
  1889.              CODE:
  1890.              /* Remove the entry from the hash */
  1891.              (void) hv_delete(Mapping, (char*)&fh, sizeof(fh), G_DISCARD) ;
  1892.  
  1893.              /* Now call the real asynch_close */
  1894.              asynch_close(fh) ;
  1895.  
  1896.      So the Perl interface would look like this
  1897.  
  1898.          sub callback1
  1899.          {
  1900.              my($handle, $buffer) = @_ ;
  1901.          }
  1902.  
  1903.          # Register the Perl callback
  1904.          asynch_read($fh, \&callback1) ;
  1905.  
  1906.          asynch_close($fh) ;
  1907.  
  1908.  
  1909.  
  1910.  
  1911.                                                                        PPPPaaaaggggeeee 22229999
  1912.  
  1913.  
  1914.  
  1915.  
  1916.  
  1917.  
  1918. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1919.  
  1920.  
  1921.  
  1922.      The mapping between the C callback and Perl is stored in the global hash
  1923.      Mapping this time. Using a hash has the distinct advantage that it allows
  1924.      an unlimited number of callbacks to be registered.
  1925.  
  1926.      What if the interface provided by the C callback doesn't contain a
  1927.      parameter which allows the file handle to Perl subroutine mapping?  Say
  1928.      in the asynchronous i/o package, the callback function gets passed only
  1929.      the buffer parameter like this
  1930.  
  1931.          void
  1932.          ProcessRead(buffer)
  1933.          char *      buffer ;
  1934.          {
  1935.              ...
  1936.          }
  1937.  
  1938.      Without the file handle there is no straightforward way to map from the C
  1939.      callback to the Perl subroutine.
  1940.  
  1941.      In this case a possible way around this problem is to predefine a series
  1942.      of C functions to act as the interface to Perl, thus
  1943.  
  1944.          #define MAX_CB              3
  1945.          #define NULL_HANDLE -1
  1946.          typedef void (*FnMap)() ;
  1947.  
  1948.          struct MapStruct {
  1949.              FnMap    Function ;
  1950.              SV *     PerlSub ;
  1951.              int      Handle ;
  1952.            } ;
  1953.  
  1954.          static void  fn1() ;
  1955.          static void  fn2() ;
  1956.          static void  fn3() ;
  1957.  
  1958.          static struct MapStruct Map [MAX_CB] =
  1959.              {
  1960.                  { fn1, NULL, NULL_HANDLE },
  1961.                  { fn2, NULL, NULL_HANDLE },
  1962.                  { fn3, NULL, NULL_HANDLE }
  1963.              } ;
  1964.  
  1965.          static void
  1966.          Pcb(index, buffer)
  1967.          int index ;
  1968.          char * buffer ;
  1969.          {
  1970.              dSP ;
  1971.  
  1972.  
  1973.  
  1974.  
  1975.  
  1976.  
  1977.                                                                        PPPPaaaaggggeeee 33330000
  1978.  
  1979.  
  1980.  
  1981.  
  1982.  
  1983.  
  1984. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  1985.  
  1986.  
  1987.  
  1988.              PUSHMARK(SP) ;
  1989.              XPUSHs(sv_2mortal(newSVpv(buffer, 0))) ;
  1990.              PUTBACK ;
  1991.  
  1992.              /* Call the Perl sub */
  1993.              perl_call_sv(Map[index].PerlSub, G_DISCARD) ;
  1994.          }
  1995.  
  1996.          static void
  1997.          fn1(buffer)
  1998.          char * buffer ;
  1999.          {
  2000.              Pcb(0, buffer) ;
  2001.          }
  2002.  
  2003.          static void
  2004.          fn2(buffer)
  2005.          char * buffer ;
  2006.          {
  2007.              Pcb(1, buffer) ;
  2008.          }
  2009.  
  2010.          static void
  2011.          fn3(buffer)
  2012.          char * buffer ;
  2013.          {
  2014.              Pcb(2, buffer) ;
  2015.          }
  2016.  
  2017.          void
  2018.          array_asynch_read(fh, callback)
  2019.              int             fh
  2020.              SV *    callback
  2021.              CODE:
  2022.              int index ;
  2023.              int null_index = MAX_CB ;
  2024.  
  2025.              /* Find the same handle or an empty entry */
  2026.              for (index = 0 ; index < MAX_CB ; ++index)
  2027.              {
  2028.                  if (Map[index].Handle == fh)
  2029.                      break ;
  2030.  
  2031.                  if (Map[index].Handle == NULL_HANDLE)
  2032.                      null_index = index ;
  2033.              }
  2034.  
  2035.              if (index == MAX_CB && null_index == MAX_CB)
  2036.                  croak ("Too many callback functions registered\n") ;
  2037.  
  2038.              if (index == MAX_CB)
  2039.                  index = null_index ;
  2040.  
  2041.  
  2042.  
  2043.                                                                        PPPPaaaaggggeeee 33331111
  2044.  
  2045.  
  2046.  
  2047.  
  2048.  
  2049.  
  2050. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2051.  
  2052.  
  2053.  
  2054.              /* Save the file handle */
  2055.              Map[index].Handle = fh ;
  2056.  
  2057.              /* Remember the Perl sub */
  2058.              if (Map[index].PerlSub == (SV*)NULL)
  2059.                  Map[index].PerlSub = newSVsv(callback) ;
  2060.              else
  2061.                  SvSetSV(Map[index].PerlSub, callback) ;
  2062.  
  2063.              asynch_read(fh, Map[index].Function) ;
  2064.  
  2065.          void
  2066.          array_asynch_close(fh)
  2067.              int     fh
  2068.              CODE:
  2069.              int index ;
  2070.  
  2071.              /* Find the file handle */
  2072.              for (index = 0; index < MAX_CB ; ++ index)
  2073.                  if (Map[index].Handle == fh)
  2074.                      break ;
  2075.  
  2076.              if (index == MAX_CB)
  2077.                  croak ("could not close fh %d\n", fh) ;
  2078.  
  2079.              Map[index].Handle = NULL_HANDLE ;
  2080.              SvREFCNT_dec(Map[index].PerlSub) ;
  2081.              Map[index].PerlSub = (SV*)NULL ;
  2082.  
  2083.              asynch_close(fh) ;
  2084.  
  2085.      In this case the functions fn1, fn2, and fn3 are used to remember the
  2086.      Perl subroutine to be called. Each of the functions holds a separate
  2087.      hard-wired index which is used in the function Pcb to access the Map
  2088.      array and actually call the Perl subroutine.
  2089.  
  2090.      There are some obvious disadvantages with this technique.
  2091.  
  2092.      Firstly, the code is considerably more complex than with the previous
  2093.      example.
  2094.  
  2095.      Secondly, there is a hard-wired limit (in this case 3) to the number of
  2096.      callbacks that can exist simultaneously. The only way to increase the
  2097.      limit is by modifying the code to add more functions and then
  2098.      recompiling.  None the less, as long as the number of functions is chosen
  2099.      with some care, it is still a workable solution and in some cases is the
  2100.      only one available.
  2101.  
  2102.      To summarize, here are a number of possible methods for you to consider
  2103.      for storing the mapping between C and the Perl callback
  2104.  
  2105.  
  2106.  
  2107.  
  2108.  
  2109.                                                                        PPPPaaaaggggeeee 33332222
  2110.  
  2111.  
  2112.  
  2113.  
  2114.  
  2115.  
  2116. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2117.  
  2118.  
  2119.  
  2120.      1. Ignore the problem - Allow only 1 callback
  2121.           For a lot of situations, like interfacing to an error handler, this
  2122.           may be a perfectly adequate solution.
  2123.  
  2124.      2. Create a sequence of callbacks - hard wired limit
  2125.           If it is impossible to tell from the parameters passed back from the
  2126.           C callback what the context is, then you may need to create a
  2127.           sequence of C callback interface functions, and store pointers to
  2128.           each in an array.
  2129.  
  2130.      3. Use a parameter to map to the Perl callback
  2131.           A hash is an ideal mechanism to store the mapping between C and
  2132.           Perl.
  2133.  
  2134.      AAAAlllltttteeeerrrrnnnnaaaatttteeee SSSSttttaaaacccckkkk MMMMaaaannnniiiippppuuuullllaaaattttiiiioooonnnn
  2135.  
  2136.      Although I have made use of only the POP* macros to access values
  2137.      returned from Perl subroutines, it is also possible to bypass these
  2138.      macros and read the stack using the ST macro (See the _p_e_r_l_x_s manpage for
  2139.      a full description of the ST macro).
  2140.  
  2141.      Most of the time the POP* macros should be adequate, the main problem
  2142.      with them is that they force you to process the returned values in
  2143.      sequence. This may not be the most suitable way to process the values in
  2144.      some cases. What we want is to be able to access the stack in a random
  2145.      order. The ST macro as used when coding an XSUB is ideal for this
  2146.      purpose.
  2147.  
  2148.      The code below is the example given in the section _R_e_t_u_r_n_i_n_g _a _l_i_s_t _o_f
  2149.      _v_a_l_u_e_s recoded to use ST instead of POP*.
  2150.  
  2151.          static void
  2152.          call_AddSubtract2(a, b)
  2153.          int a ;
  2154.          int b ;
  2155.          {
  2156.              dSP ;
  2157.              I32 ax ;
  2158.              int count ;
  2159.  
  2160.              ENTER ;
  2161.              SAVETMPS;
  2162.  
  2163.              PUSHMARK(SP) ;
  2164.              XPUSHs(sv_2mortal(newSViv(a)));
  2165.              XPUSHs(sv_2mortal(newSViv(b)));
  2166.              PUTBACK ;
  2167.  
  2168.              count = perl_call_pv("AddSubtract", G_ARRAY);
  2169.  
  2170.  
  2171.  
  2172.  
  2173.  
  2174.  
  2175.                                                                        PPPPaaaaggggeeee 33333333
  2176.  
  2177.  
  2178.  
  2179.  
  2180.  
  2181.  
  2182. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2183.  
  2184.  
  2185.  
  2186.              SPAGAIN ;
  2187.              SP -= count ;
  2188.              ax = (SP - PL_stack_base) + 1 ;
  2189.  
  2190.              if (count != 2)
  2191.                  croak("Big trouble\n") ;
  2192.  
  2193.              printf ("%d + %d = %d\n", a, b, SvIV(ST(0))) ;
  2194.              printf ("%d - %d = %d\n", a, b, SvIV(ST(1))) ;
  2195.  
  2196.              PUTBACK ;
  2197.              FREETMPS ;
  2198.              LEAVE ;
  2199.          }
  2200.  
  2201.      Notes
  2202.  
  2203.      1.   Notice that it was necessary to define the variable ax.  This is
  2204.           because the ST macro expects it to exist.  If we were in an XSUB it
  2205.           would not be necessary to define ax as it is already defined for
  2206.           you.
  2207.  
  2208.      2.   The code
  2209.  
  2210.                   SPAGAIN ;
  2211.                   SP -= count ;
  2212.                   ax = (SP - PL_stack_base) + 1 ;
  2213.  
  2214.           sets the stack up so that we can use the ST macro.
  2215.  
  2216.      3.   Unlike the original coding of this example, the returned values are
  2217.           not accessed in reverse order.  So ST(0) refers to the first value
  2218.           returned by the Perl subroutine and ST(count-1) refers to the last.
  2219.  
  2220.      CCCCrrrreeeeaaaattttiiiinnnngggg aaaannnndddd ccccaaaalllllllliiiinnnngggg aaaannnn aaaannnnoooonnnnyyyymmmmoooouuuussss ssssuuuubbbbrrrroooouuuuttttiiiinnnneeee iiiinnnn CCCC
  2221.  
  2222.      As we've already shown, perl_call_sv can be used to invoke an anonymous
  2223.      subroutine.  However, our example showed how Perl script invoking an XSUB
  2224.      to preform this operation.  Let's see how it can be done inside our C
  2225.      code:
  2226.  
  2227.       ...
  2228.  
  2229.       SV *cvrv = perl_eval_pv("sub { print 'You will not find me cluttering any namespace!' }", TRUE);
  2230.  
  2231.       ...
  2232.  
  2233.       perl_call_sv(cvrv, G_VOID|G_NOARGS);
  2234.  
  2235.      perl_eval_pv is used to compile the anonymous subroutine, which will be
  2236.      the return value as well (read more about perl_eval_pv in the
  2237.      perl_eval_pv entry in the _p_e_r_l_g_u_t_s manpage).  Once this code reference is
  2238.  
  2239.  
  2240.  
  2241.                                                                        PPPPaaaaggggeeee 33334444
  2242.  
  2243.  
  2244.  
  2245.  
  2246.  
  2247.  
  2248. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2249.  
  2250.  
  2251.  
  2252.      in hand, it can be mixed in with all the previous examples we've shown.
  2253.  
  2254. SSSSEEEEEEEE AAAALLLLSSSSOOOO
  2255.      the _p_e_r_l_x_s manpage, the _p_e_r_l_g_u_t_s manpage, the _p_e_r_l_e_m_b_e_d manpage
  2256.  
  2257. AAAAUUUUTTTTHHHHOOOORRRR
  2258.      Paul Marquess <_p_m_a_r_q_u_e_s_s@_b_f_s_e_c._b_t._c_o._u_k>
  2259.  
  2260.      Special thanks to the following people who assisted in the creation of
  2261.      the document.
  2262.  
  2263.      Jeff Okamoto, Tim Bunce, Nick Gianniotis, Steve Kelem, Gurusamy Sarathy
  2264.      and Larry Wall.
  2265.  
  2266. DDDDAAAATTTTEEEE
  2267.      Version 1.3, 14th Apr 1997
  2268.  
  2269.  
  2270.  
  2271.  
  2272.  
  2273.  
  2274.  
  2275.  
  2276.  
  2277.  
  2278.  
  2279.  
  2280.  
  2281.  
  2282.  
  2283.  
  2284.  
  2285.  
  2286.  
  2287.  
  2288.  
  2289.  
  2290.  
  2291.  
  2292.  
  2293.  
  2294.  
  2295.  
  2296.  
  2297.  
  2298.  
  2299.  
  2300.  
  2301.  
  2302.  
  2303.  
  2304.  
  2305.  
  2306.  
  2307.                                                                        PPPPaaaaggggeeee 33335555
  2308.  
  2309.  
  2310.  
  2311.  
  2312.  
  2313.  
  2314. PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))                                                        PPPPEEEERRRRLLLLCCCCAAAALLLLLLLL((((1111))))
  2315.  
  2316.  
  2317.  
  2318.  
  2319.  
  2320.  
  2321.  
  2322.  
  2323.  
  2324.  
  2325.  
  2326.  
  2327.  
  2328.  
  2329.  
  2330.  
  2331.  
  2332.  
  2333.  
  2334.  
  2335.  
  2336.  
  2337.  
  2338.  
  2339.  
  2340.  
  2341.  
  2342.  
  2343.  
  2344.  
  2345.  
  2346.  
  2347.  
  2348.  
  2349.  
  2350.  
  2351.  
  2352.  
  2353.  
  2354.  
  2355.  
  2356.  
  2357.  
  2358.  
  2359.  
  2360.  
  2361.  
  2362.  
  2363.  
  2364.  
  2365.  
  2366.  
  2367.  
  2368.  
  2369.  
  2370.                                                                        PPPPaaaaggggeeee 33336666
  2371.  
  2372.  
  2373.  
  2374.  
  2375.  
  2376.  
  2377.